package com.zby.scms.controller;

import com.alibaba.fastjson.JSONObject;
import com.zby.scms.entity.User;
import com.zby.scms.utils.BaseResult;
import com.zby.scms.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 登录控制器
 */

@Api (tags = "用户实体(login)")
@RestController
//@RequestMapping("login")
public class LoginController {

    @ApiOperation (value = "登录认证")
    @PostMapping("/auth")
    public BaseResult<User> authLogin(@RequestBody User user){//@RequestParam(value = "userid")String userid, @RequestParam(value = "password")String password
//        User user=new User();
//        user.setUserid(userid);
//        user.setPassword(password);
//        List<User> list = null;
//        list.add(user);
        System.out.println(user.getPassword()+user.getUserid());
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUserid(),user.getPassword()
        );
        //登录
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);

//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (IncorrectCredentialsException e) {

            return ResultUtil.error("密码错误");
        } catch (LockedAccountException e) {

            return ResultUtil.error("登录失败，该用户已被冻结");
        }catch (AuthenticationException e) {

            return ResultUtil.error("该用户不存在");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("厉害了。。。。。。。。。。。。。。。。。。。。。:"+user.getClass());
        return ResultUtil.success(user);


    }

    @ApiOperation (value = "退出登录&跳到登录页面")
    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "退出成功";
    }

    @RequestMapping("/noauth")
    public String noauth(){
        return "未授权";
    }




}
